'use strict';

const Service = require('egg').Service;

class MenuService extends Service {

  // 新增
  async create(payload) {
    const { app } = this;
    return await app.model.Menu.create(payload);
  }

  // 获取列表
  async getList(pageNum, pageSize) {
    const { app, ctx } = this;
    try {
      const offset = (pageNum - 1) * pageSize;
      const { count, rows } = await app.model.Menu.findAndCountAll({
        // attributes: [
        //   'id',
        //   'name',
        //   'url',
        //   'pic',
        //   'stutas',
        // ],
        raw: true,
        offset,
        limit: pageSize * 1,
      });
      return {
        pageNum,
        pageSize,
        total: count,
        list: ctx.helper.toTree(rows),
      };
    } catch (error) {
      console.error(error);
      return null;
    }
  }

  // 删除
  async del(payload) {
    const { app } = this;
    const res = await app.model.Menu.findAll({
      where: { parentId: payload.ids },
    });
    // 如果当前删除id有子菜单
    if (res.length > 0) {
      const err = new Error('删除失败，当前菜单存在子菜单。');
      err.parent = {};
      err.parent.errno = 1451;
      throw err;
    }
    return await app.model.Menu.destroy({ where: { id: payload.ids }, force: true });
  }

  // 根据id获取信息
  async getInfo(id) {
    return await this.app.model.Menu.findByPk(id);
  }

  // 修改
  async updated(id, payload) {
    const { app } = this;
    return await app.model.Menu.update(payload, { where: { id } });
  }


  /**
   * 根据角色获取菜单
   * @return {Promise<*[]|*>}
   */
  async userMenus() {
    const { app, ctx } = this;
    let data = await app.model.User.findAll({
      include: [
        {
          model: app.model.Role,
          include: [
            {
              model: app.model.Menu,
              attributes: {
                exclude: [ 'createdAt', 'updatedAt' ],
              },
            },
          ],
        },
      ],
      where: {
        id: ctx.state.user.id,
      },
      raw: false,
    });
    // 如果没有则直接返回空数组
    if (data.length === 0) {
      return [];
    }
    data = data[0].role;
    // 去重
    const arr = [];
    data.forEach((e, i) => {
      e.menu.forEach((ee, ii) => {
        ee.__role = {
          id: e.id,
          name: e.name,
        };
        arr.push(ee);
      });
    });
    data = app.lodash.uniqWith(arr, (a, b) => a.id === b.id);
    data = data.sort((a, b) => b.sort - a.sort);
    return data;
  }

}

module.exports = MenuService;
